using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.Office.Server.Search.Query;
using System.Data;
using System.IO;
using System.Text;
using System.Xml.Xsl;
using System.Xml;

namespace SearchWebPart
{
    [Guid("f0a6a9f9-cf81-4824-add7-82e0cdac122e")]
    public class SearchWebPart : System.Web.UI.WebControls.WebParts.WebPart
    {
        private string myQuery;

        [WebBrowsable(true),Personalizable(), WebDisplayName("Your query")]
        public string Query
        {
            get { return myQuery; }
            set { myQuery = value; }
        }


        private string xsl;

        [WebBrowsable(true), Personalizable(), WebDisplayName("XSL Formatting code")]
        public string FormatStylesheet
        {
            get { return xsl; }
            set { xsl = value; }
        }
	

        protected override void CreateChildControls()
        {
            base.CreateChildControls();         
        }

        protected override void Render(HtmlTextWriter writer)
        {
            try
            {

                FullTextSqlQuery ftsq = new FullTextSqlQuery(SPContext.Current.Site);

              //  ftsq.AuthenticationType = QueryAuthenticationType.NtAuthenticatedQuery;
                ftsq.QueryText = myQuery;
                ftsq.RowLimit = 4000;
                ftsq.ResultTypes = ResultType.RelevantResults;
               
                ResultTableCollection rtc = ftsq.Execute();
                
                DataSet ds = new DataSet();
                DataTable dt = new DataTable();
                dt.Load(rtc[ResultType.RelevantResults]);
                ds.Tables.Add(dt);

                if (xsl != null)
                {
                    StringBuilder sb = new StringBuilder();
                    StringWriter sw = new StringWriter(sb);

                    ds.WriteXml(sw, XmlWriteMode.IgnoreSchema);
                    sw.Flush();

                    StringReader sr = new StringReader(xsl);
                    XmlReader rdr = XmlReader.Create(sr);

                    XslTransform xslt = new XslTransform();
                    xslt.Load(rdr);

                    XmlDocument xmldoc = new XmlDocument();
                    xmldoc.LoadXml(sb.ToString());

                    xslt.Transform(xmldoc, null, writer, null);
                }
                else
                    ds.WriteXml(writer);
                
                //xslt.Load(

                //writer.WriteEncodedText(sb.ToString());
                
            }
            catch (Exception err)
            {
                writer.Write(err.Message);
            }
        }
    }
}
